<?php
namespace control;
/*
*社保核算类
*/

class insureClass extends adIndexClass
{
    private const title = '社保核算';
    private const page = 'insure';
    private const table = 'insure';
    public string $checkIdCard = "/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/";

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        if ($workFlow == L('salary.table.she_bao_ji_lu')) {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]) .
                repeatSelect(array("name" => "subject", "title" => L('salary.table.fei_kuan_ke_mu'), 'sqlForm' => self::table, 'sqlField' => 'subject')) .
                text(array("name" => "payMoon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => L('salary.table.jkyf'))) .
                text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => L('salary.table.zsyf'))) .
                select(array("name" => "orderBy", "title" => L('salary.table.pai_xu'), "option" => array('缴款月份' => L('salary.table.jkyf'), '所属月份' => L('salary.table.zsyf'))));
        } else {
            $html =
                selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('salary.table.xing_ming')]) .
                selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('salary.table.bu_men')]);
        }

        return $this->search($html, 'menu');
    }

    /**
     * 设备扣款
     *
     */
    public function deduction(): bool|string
    {
        $json['html'] = $this->homeForm('社保扣款');
        return json_encode($json, 320);
    }

    public function deductionSearch(): bool|string
    {
        //月份
        $payMoon = date("Y-m");
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
            'workFlow'=>'已复核',
        );
        $and = " and (quitDay is null or date_format(quitDay,'%Y-%m') >='$payMoon')";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        //获取表头
        $checkAll = $this->checkAll("lastMoneyCutForm", "stid");
        //表头
        $tr[] = array($checkAll, L('salary.table.cbyg'), L('salary.table.deylbx'), L('salary.table.jbylbx'), L('salary.table.ylbx'), L('salary.table.gsbx'), L('salary.table.shi_ye_bao_xian'), L('salary.table.he_ji'), L('salary.table.zhkk'));
        $tdText[] = array(" rowspan='2' ", " colspan='3' ", " colspan='2' ", " colspan='3' ", " colspan='2' ", "", " colspan='2' ", " colspan='2' ", " colspan='2' ");
        $tr[] = array('', L('salary.table.zsbm'), L('salary.table.dqzw'), L('salary.table.xing_ming'), L('salary.table.ge_ren_jiao_fei'), L('salary.table.dwtc'), L('salary.table.ge_ren_jiao_fei'), L('salary.table.dwzh'), L('salary.table.dwtc'), L('salary.table.ge_ren_jiao_fei'), L('salary.table.dwjf'), L('salary.table.dwjf'), L('salary.table.ge_ren_jiao_fei'), L('salary.table.dwtc'), L('salary.table.ge_ren_jiao_fei'), L('salary.table.dwjf'), L('salary.table.zhkk'), L('salary.table.bei_zhu'));
        $tdText[] = array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");

        //检索数据
        $lastMoneyAll = 0;
        $sql = find(array("table" => "staff", "where" => " 1=1 $where order by time "));

        foreach ($sql['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "stid", "value" => $array['stid']),
            );
            $record = query(self::table . '_record', " staffId = '$array[stid]' and month = '{$payMoon}'");
            if (empty($record['id'])) {
                //数据准备
                $job = query("job", " id = '$array[jobId]' ");
                $department = query("department", " id = '$job[departmentId]' ");
                //大额医疗保险个人缴费
                $medicareBigPersonal = find(array("table" => "insure", "sum" => "personal", "where" => " stid = '$array[stid]' and subject = '大额医疗保险' and payMoon = '$payMoon' order by moon "));
                //大额医疗保险单位统筹
                $medicareBigCompany = find(array("table" => "insure", "sum" => "fund", "where" => " stid = '$array[stid]' and subject = '大额医疗保险' and payMoon = '$payMoon' order by moon "));
                //基本医疗保险个人缴费
                $medicareBasicPersonal = find(array("table" => "insure", "sum" => "personal", "where" => " stid = '$array[stid]' and subject = '基本医疗保险' and payMoon = '$payMoon' order by moon "));
                //基本医疗保险单位账户
                $medicareBasicCompanyAccount = find(array("table" => "insure", "sum" => "company", "where" => " stid = '$array[stid]' and subject = '基本医疗保险' and payMoon = '$payMoon' order by moon "));
                //基本医疗保险单位统筹
                $medicareBasicCompanyPlan = find(array("table" => "insure", "sum" => "fund", "where" => " stid = '$array[stid]' and subject = '基本医疗保险' and payMoon = '$payMoon' order by moon "));
                //养老保险个人缴费
                $pensionPersonal = find(array("table" => "insure", "sum" => "personal", "where" => " stid = '$array[stid]' and subject = '养老保险' and payMoon = '$payMoon' order by moon "));
                //养老保险单位缴费
                $pensionCompany = find(array("table" => "insure", "sum" => "company", "where" => " stid = '$array[stid]' and subject = '养老保险' and payMoon = '$payMoon' order by moon "));
                //工伤保险单位缴费
                $injuryWork = find(array("table" => "insure", "sum" => "company", "where" => " stid = '$array[stid]' and subject = '工伤保险' and payMoon = '$payMoon' order by moon "));
                //失业保险个人缴费
                $unemploymentPersonal = find(array("table" => "insure", "sum" => "personal", "where" => " stid = '$array[stid]' and subject = '失业保险' and payMoon = '$payMoon' order by moon "));
                //失业保险个人补退
                $unemploymentPersonalGiveBack = find(array("table" => "insure", "sum" => "personal", "where" => " stid = '$array[stid]' and subject = '失业保险个人补退' and payMoon = '$payMoon' order by moon "));
                //失业保险单位统筹
                $unemploymentCompany = find(array("table" => "insure", "sum" => "fund", "where" => " stid = '$array[stid]' and subject = '失业保险' and payMoon = '$payMoon' order by moon "));
                //单位缴费合计
                $companyAll = $medicareBigCompany + $medicareBasicCompanyAccount + $medicareBasicCompanyPlan + $pensionCompany + $injuryWork + $unemploymentCompany;
                //个人缴费合计
                $personalAll = $medicareBigPersonal + $medicareBigPersonal + $pensionPersonal + $unemploymentPersonal + $unemploymentPersonalGiveBack;
                if ($array['state'] == "离职") {
                    $personalAll += $companyAll;
                }
                $lastMoneyAll += $personalAll;
                //员工结算账户社保扣款
                $lastMoney = text(array("name" => "lastMoneyCut[$array[stid]]", "class" => "text textPrice", "value" => $personalAll));
                //生成本列
                $tr[] = array($this->dominate($dominate), $department['name'], $job['name'], $array['name'],
                    $medicareBigPersonal, $medicareBigCompany,
                    $medicareBasicPersonal, $medicareBasicCompanyAccount, $medicareBasicCompanyPlan,
                    $pensionPersonal, $pensionCompany,
                    $injuryWork,
                    $unemploymentPersonal, $unemploymentCompany,
                    $personalAll, $companyAll, $lastMoney,
                    text(array('name' => "text[$array[stid]]", "class" => "text textPrice", 'value' => $array['text']))
                );
                $tdText[] = array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            }
        }
        $button = '';
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'commitDec', {})\">" . L('clock.table.decMoney') . "</span>\n";
        }
        //生成页面
        $json['html'] = $button . space . "<form name='lastMoneyCutForm'>" . $this->tableMany(array("tr" => $tr, "text" => $tdText)) . "</form>";
        //返回
        return json_encode($json, 320);
    }

    /**
     * 提交扣款
     * @return bool|string
     */
    public function commitDec(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') => L('salary.table.tax_warn'),
            ),
        ), 'formTwo' => 'lastMoneyCutForm'));
        //返回
        return $this->layer(array("title" => L('salary.table.zhkk'), "height" => 160, "width" => 600, "html" => $html));
    }

    /**
     * 账户扣款编辑
     * @return bool|string
     */
    public function commitDecEdit()
    {
        $listId = $this->post('stid');
        $textArr = $this->post('text');
        $decMoneyArr = $this->post('lastMoneyCut');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('salary.table.insure_edit_permission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        } else {
            $x = 0;
            $payMoon = date('Y-m');
            foreach ($listId as $stid) {
                $staff = query('staff', " stid = '$stid'");
                $insure = query(self::table, "stid = '$stid' and payMoon = '$payMoon'");
                if (empty($insure['moon'])) {
                    //添加日志
                    $text = str_replace(['{{staffName}}', '{{name}}', '{{payMoon}}'], [$this->control['name'], $staff['name'], $payMoon], L('salary.table.insure_dec_text'));
                } else {
                    $id = self::getId();
                    $warn = insert(array(
                        "table" => self::table . '_record',
                        "field" => [
                            'id' => $id,
                            'staffId' => $stid,
                            'decMoney' => $decMoneyArr[$stid],
                            'text' => $textArr[$stid],
                            'stid' => $this->control['stid'],
                            'month' => $payMoon,
                            'belongMonth' => $insure['moon'],
                            'time' => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        //添加日志
                        $text = str_replace(['{{staffName}}', '{{name}}', '{{payMoon}}', '{{id}}'], [$this->control['name'], $staff['name'], $payMoon, $id], L('salary.table.insure_dec_suc'));
                    } else {
                        $text = str_replace(['{{staffName}}', '{{name}}', '{{payMoon}}', '{{payMoon}}'], [$this->control['name'], $staff['name'], $payMoon], L('salary.table.insure_dec_error'));
                    }
                }
                $this->logText(["type" => self::page, "text" => $text]);
            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.insure_dec_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&menu=deduction&id=all";
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 查询条件
     *
     * @param string $workFlow
     * @return string
     */
    public function home($workFlow = '社保记录'): string
    {
        if ($workFlow == '社保记录') {
            $data = [
                "id" => "all",
                "menu" => [
                    "record" => L('salary.table.she_bao_ji_lu'),
                    "deduction" => L('salary.table.sbkk'),
                ]
            ];
        }
        $data['html'] = $this->homeForm('社保记录');
        return $this->tab($data);
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
            "subject" => $this->post('subject'),//费款科目
        );
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('payMoon')) {
            $timeArr = explode(' ~ ', $this->post('payMoon'));
            $and .= " and payMoon >='{$timeArr[0]}' and payMoon <='{$timeArr[1]}'";
        }
        if ($this->post('moon')) {
            $timeArr = explode(' ~ ', $this->post('moon'));
            $and .= " and moon >='{$timeArr[0]}' and moon <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy') ?? null,
            "default" => '缴款月份',
            "array" => array(
                "payMoon" => array("desc" => '缴款月份', "site" => 4),
                "moon" => array("desc" => '所属月份', "site" => 5),
                "time" => array("desc" => '创建日期', "site" => ''),
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('salary.table.yuan_gong'), L('salary.table.fei_kuan_ke_mu'), L('salary.table.jkyf'), L('salary.table.zsyf'), "缴费基数(". static::$unit . ")", "个人缴纳(". static::$unit . ")", "单位缴帐户(". static::$unit . ")", "单位缴统筹(". static::$unit . ")", L('salary.table.jflb'));
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            //数据库查询
            $staff = query("staff", " stid = '$array[stid]' ");
            //本行
            $tr[] = array($this->dominate($dominate), $staff['name'], $array['subject'], $array['payMoon'], $array['moon'], $array['base'], $array['personal'], $array['company'], $array['fund'], $array['type']);
        }
        //控件
        $button = "";
        //导入
        if ($this->power("insure", "edit")) {
            $button .=
                importTemplateClass::importTemplateButton(self::page) .
                $this->upButton(array("title" => L('salary.table.import_me'), "fun" => "medicalInsuranceUpload")) .
                $this->upButton(array("title" => L('salary.table.import_yang'), "fun" => "endowmentInsurance")) .
                $this->upButton(array("title" => L('salary.table.import_gong'), "fun" => "InjuryUpload")) .
                $this->upButton(array("title" => L('salary.table.import_shi'), "fun" => "unemploymentUpload")) .
                $this->upButton(array("title" => L('salary.table.import_but'), "fun" => "unemploymentPersonalUpload"));
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr, "orderBySign" => $orderBy)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    /*导入按钮
    $data = array(
        "title" => "按钮标题",
        "fun" => "csv导入分析函数",
    );
    */
    public function upButton($data): string
    {
        //表单名称
        $form = self::getId() . "UpForm";
        //HTML内容
        $html = "
		<span class='spanButton' onclick=\"document." . $form . ".file.click()\">" . $data['title'] . "</span>
		<form name='" . $form . "' class='hide' method='post' enctype='multipart/form-data' action='" . root . "control/adIndex.html?cla=insure&fun=" . $data['fun'] . "'>
			<input name='file' type='file' onchange='document." . $form . ".submit()'>
		</form>
		";
        return $html;
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('salary.table.nhmzbjdzx');
        } else {
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.insure_import_model'));
            $this->logText(["type" => self::page, "text" => $text]);
            $title = [L('salary.table.ge_ren_bian_hao'), L('salary.table.xing_ming'), L('salary.table.zjhm'), L('salary.table.feeSubject'), L('salary.table.feeBelong'), L('salary.table.money_belong'), L('salary.table.jiao_fei_ji_shu'), L('salary.table.he_ji'), L('salary.table.ge_ren_jiao_na'), L('salary.table.dwjzh'), L('salary.table.dwjtc'), L('salary.table.grjfbz'), L('salary.table.dwjfbz'), L('salary.table.rylb'), L('salary.table.nian_ling'), L('salary.table.jflb')];

            $temp = ini_get('upload_tmp_dir');
            if ($temp !== false && file_exists($temp)) {
                $tempDir = realpath($temp);
            } else {
                $tempDir = realpath(sys_get_temp_dir());
            }
            $config = [];
            if (PHP_OS == 'Linux') {
                $config = [
                    'path' => $tempDir . '/',
                ];
            } elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                //windows环境
                $config = [
                    'path' => $tempDir,
                ];
            }

            $excel = new \Vtiful\Kernel\Excel($config);
            $fileObject = $excel->fileName(L('salary.table.import_title') . ".xlsx", L('salary.table.medical'));
            $fileObject->header($title)
                ->data([]);
            //养老保险
            $title = [L('salary.table.dwbh'), L('salary.table.ge_ren_bian_hao'), L('salary.table.xing_ming'), L('salary.table.zjhm'), L('salary.table.feeBelong'), L('salary.table.money_belong'), L('salary.table.jiao_fei_ji_shu'), L('salary.table.grjfje'), L('salary.table.dwjfje'), L('salary.table.jflb'), L('salary.table.jfbz')];
            $fileObject->addSheet(L('salary.table.ylbx'))
                ->header($title)
                ->data([]);

            //失业保险
            $title = [L('salary.table.dwbh'), L('salary.table.ge_ren_bian_hao'), L('salary.table.xing_ming'), L('salary.table.zjhm'), L('salary.table.feeBelong'), L('salary.table.money_belong'), L('salary.table.jiao_fei_ji_shu'), L('salary.table.jiao_fei_jin_e'), L('salary.table.kuangxiang'), L('salary.table.jflb')];
            $fileObject->addSheet(L('salary.table.shi_ye_bao_xian'))
                ->header($title)
                ->data([]);

//            //失业保险-补退
            $title = [L('salary.table.dwbh'), L('salary.table.ge_ren_bian_hao'), L('salary.table.xing_ming'), L('salary.table.zjhm'), L('salary.table.feeBelong'), L('salary.table.money_belong'), L('salary.table.jiao_fei_ji_shu'), L('salary.table.jiao_fei_jin_e'), L('salary.table.kuangxiang'), L('salary.table.jflb')];
            $fileObject->addSheet(L('salary.table.butui'))
                ->header($title)
                ->data([]);

//            //工伤保险
            $title = [L('salary.table.dwbh'), L('salary.table.grsbh'), L('salary.table.xing_ming'), L('salary.table.zjhm'), L('salary.table.feeBelong'), L('salary.table.money_belong'), L('salary.table.jiao_fei_ji_shu'), L('salary.table.dwjfje'), L('salary.table.jflb')];
            $fileObject->addSheet(L('salary.table.gsbx'))
                ->header($title)
                ->data([]);

            $filePath = $fileObject->output();
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                //windows环境
                $filePath = str_replace("/", "\\", $filePath);
//                $filePath = iconv("UTF-8", "GBK//IGNORE", $filePath);
            }
            header("Content-Type: applicationnd.openxmlformats-officedocument.spreadsheetml.sheet");
            header('Content-Disposition: attachment;filename="社保导入模板.xlsx"');
            header('Cache-Control: max-age=0');
            ob_clean();
            flush();
            if (copy($filePath, 'php://output') === false) {
                // Throw exception
            }
            @unlink($filePath);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析-医疗保险*/
    public function medicalInsuranceUpload()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('salary.table.nhmzbjdzx');
        } else {
            $data = $this->importHead(format: [
                2 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $x = 0;
            $log = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $IDCard = $cell[2];//身份证号码
                    $talent = query('talent_pool', " idCard = '$IDCard'");
                    $staff = query("staff", "talentId = '$talent[id]'");
                    $num = $i + 1;//当前行
                    $payMoon = date("Y-m", strtotime($cell[4] . "01"));//缴款月份
                    $moon = date("Y-m", strtotime($cell[5] . "01"));//所属月份

                    $field = [
                        "id" => suiji(),
                        "stid" => $staff['stid'],//员工ID
                        "subject" => $cell[3],//费款科目
                        "payMoon" => $payMoon,//缴款月份
                        "moon" => $moon,//所属月份
                        "base" => $cell[6],//缴费基数
                        "personal" => $cell[8],//个人缴纳
                        "company" => $cell[9],//单位缴帐户
                        "fund" => $cell[10],//单位缴统筹
                        "type" => $cell[15],//缴费类别
                    ];
                    $annotation = [
                        'stid' => L('salary.table.yuan_gong'),
                        'subject' => L('salary.table.fei_kuan_ke_mu'),
                        'payMoon' => L('salary.table.jkyf'),
                        'moon' => L('salary.table.zsyf'),
                    ];
                    $rules = [
                        'stid' => 'required',
                        'subject' => 'required',
                        'payMoon' => 'required',
                        'moon' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    $line = str_replace(['{{i}}'], [$num], L('job.other.line'));
                    if ($result === false) {
                        $log .= "\n" . $line . "：" . $vt->getErrs()[0];  // 多个规则提示最前面一条
                    } elseif (preg_match($this->checkIdCard, $IDCard) == 0) {
                        $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                    } elseif (sqlNum("insure", "stid = '$field[stid]' and subject = '$field[subject]' and payMoon = '$payMoon' and moon = '$moon' ") > 0) {
                        $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.exist_data'));
                    } elseif (empty($cell[4])) {
                        $log .= "\n" . $line . "：" . L('salary.table.no_pay_month');
                    } elseif (empty($cell[5])) {
                        $log .= "\n" . $line . "：" . L('salary.table.no_belong_month');
                    } elseif (!empty($cell[6]) && preg_match(checkPrice, $cell[6]) == 0) {
                        $log .= "\n" . $line . "：" . L('salary.table.feeBaseError');
                    } elseif (!empty($cell[8]) && preg_match(checkPrice, $cell[8]) == 0) {
                        $log .= "\n" . $line . "：" . L('salary.table.personError');
                    } else {
                        $warn = insert(array(
                            "table" => "insure",
                            "field" => $field
                        ));
                        if ($warn == '新增成功') {
                            $x++;
                            $log .= "\n" . $line . "：" . L('job.other.import_success') . "<br>";
                        } else {
                            $log .= "\n" . $line . "：" . L('job.other.import_failed') . "<br>";
                        }
                    }
                }
            }
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /*数据导入分析-养老保险*/
    public function endowmentInsurance()
    {
        if (!$this->power(self::page, 'edit')) {
            $warn = L('salary.table.nhmzbjdzx');
        } else {
            $data = $this->importHead(format: [
                3 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $x = 0;
            $log = '';
            foreach ($data as $i => $row) {
                $num = $i + 1;//当前行
                $cell = formSubArray($row);
                $IDCard = $cell[3];//身份证号码
                $talent = query('talent_pool', " idCard = '$IDCard'");
                $staff = query("staff", "talentId = '$talent[id]'");
                $payMoon = date("Y-m", strtotime($cell[4] . "01"));//缴款月份
                $moon = date("Y-m", strtotime($cell[5] . "01"));//所属月份
                $line = str_replace(['{{i}}'], [$num], L('job.other.line'));
                if (preg_match($this->checkIdCard, $IDCard) == 0) {
                    $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                } elseif (empty($staff['stid'])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_staff');
                } elseif (sqlNum("insure", "stid = '$staff[stid]' and subject = '养老保险' and payMoon = '$payMoon' and moon = '$moon' ") > 0) {
                    $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.exist_data'));
                } elseif (empty($cell[4])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_pay_month');
                } elseif (empty($cell[5])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_belong_month');
                } elseif (!empty($cell[6]) && preg_match(checkPrice, $cell[6]) == 0) {
                    $log .= "\n" . $line . "：" . L('salary.table.feeBaseError');
                } elseif (!empty($cell[7]) && preg_match(checkPrice, $cell[7]) == 0) {
                    $log .= "\n" . $line . "：" . L('salary.table.personError');
                } else {
                    insert(array(
                        "table" => "insure",
                        "field" => array(
                            "id" => suiji(),
                            "stid" => $staff['stid'],//员工ID
                            "subject" => '养老保险',//费款科目
                            "payMoon" => $payMoon,
                            "moon" => $moon,
                            "base" => $cell[6],//缴费基数
                            "personal" => $cell[7],//个人缴纳
                            "company" => $cell[8],//单位缴帐户
                            "fund" => 0,//单位缴统筹
                            "type" => $cell[9],//缴费类别
                            "time" => date("Y-m-d H:i:s"),
                        ),
                    ));
                    $x++;
                }
            }
            //添加日志
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(array("type" => "insure", "text" => $text));
            //提示
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
        }
        $_SESSION['warn'] = $warn;
        header("location:" . root . "control/adIndex.html?cla=insure&fun=home");
        exit(0);
    }

    /*数据导入分析-工伤保险*/
    public function InjuryUpload()
    {
        if (!$this->power(self::page, 'edit')) {
            $warn = L('salary.table.nhmzbjdzx');
        } else {
            $data = $this->importHead(format: [
                3 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $log = "";
            $x = 0;
            foreach ($data as $key => $row) {
                $num = $key + 1;//当前行
                $cell = formSubArray($row);
                $IDCard = $cell[3];//身份证号
                $talent = query('talent_pool', " idCard = '$IDCard'");
                $staff = query("staff", "talentId = '$talent[id]'");
                $payMoon = date("Y-m", strtotime($cell[4] . "01"));//缴款月份
                $moon = date("Y-m", strtotime($cell[5] . "01"));//所属月份
                $line = str_replace(['{{i}}'], [$num], L('job.other.line'));
                if (preg_match($this->checkIdCard, $IDCard) == 0) {
                    $log .="\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                } elseif (empty($staff['stid'])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_staff');
                } elseif (sqlNum("insure", "stid = '$staff[stid]' and subject = '工伤保险' and payMoon = '$payMoon' and moon = '$moon' ") > 0) {
                    $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.exist_data'));
                } elseif (empty($cell[4])) {
                    $log .=  "\n" . $line . "：" . L('salary.table.no_pay_month');
                } elseif (empty($cell[5])) {
                    $log .=  "\n" . $line . "：" . L('salary.table.no_belong_month');
                } elseif (!empty($cell[6]) && preg_match(checkPrice, $cell[6]) == 0) {
                    $log .= "\n" . $line . "：" . L('salary.table.feeBaseError');
                } else {
                    insert(array(
                        "table" => "insure",
                        "field" => array(
                            "id" => suiji(),
                            "stid" => $staff['stid'],//员工ID
                            "subject" => '工伤保险',//费款科目
                            "payMoon" => $payMoon,
                            "moon" => $moon,
                            "base" => $cell[6],//缴费基数
                            "personal" => 0,//个人缴纳
                            "company" => $cell[7],//单位缴帐户
                            "fund" => 0,//单位缴统筹
                            "type" => $cell[8],//缴费类别
                            "time" => date("Y-m-d H:i:s"),
                        ),
                    ));
                    $x++;
                }
            }
            //添加日志
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(array("type" => "insure", "text" => $text));
            //提示
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
        }
        $_SESSION['warn'] = $warn;
        header("location:" . root . "control/adIndex.html?cla=insure&fun=home");
        exit(0);
    }

    /*数据导入分析-失业保险*/
    public function unemploymentUpload()
    {
        if (!$this->power(self::page, 'edit')) {
            $warn = L('salary.table.nhmzbjdzx');
        } else {
            $data = $this->importHead(format: [
                3 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $log = "";
            $x = 0;
            foreach ($data as $key => $row) {
                $num = $key + 1;//当前行
                $line = str_replace(['{{i}}'], [$num], L('job.other.line'));
                $cell = formSubArray($row);
                $IDCard = $cell[3];//身份证号
                $talent = query('talent_pool', " idCard = '$IDCard'");
                $staff = query("staff", "talentId = '$talent[id]'");
                $payMoon = date("Y-m", strtotime($cell[4] . "01"));//缴款月份
                $moon = date("Y-m", strtotime($cell[5] . "01"));//所属月份
                $insure = query("insure", " stid = '$staff[stid]' and subject = '失业保险' and payMoon = '$payMoon' and moon = '$moon' ");
                if (preg_match($this->checkIdCard, $IDCard) == 0) {
                    $log .="\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                } elseif (empty($staff['stid'])) {
                    $log .=   $log .= "\n" . $line . "：" . L('salary.table.no_staff');
                } /*elseif ($staff['socialSecurity'] != '是') {
                    $log .= "\n" . $num . "：".str_replace(['{{name}}'],[$staff['name']],L('salary.table.no_staff'));
                } */elseif (empty($cell[4])) {
                    $log .="\n" . $line . "：" . L('salary.table.no_pay_month');
                } elseif (empty($cell[5])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_belong_month');
                } elseif (!empty($cell[6]) && preg_match(checkPrice, $cell[6]) == 0) {
                    $log .= "\n" . $line . "：" . L('salary.table.feeBaseError');
                } elseif (empty($insure['id'])) {
                    if ($cell[8] == '单位缴统筹') {
                        $personal = 0;
                        $fund = $cell[7];
                    } elseif ($cell[8] == '个人缴纳') {
                        $personal = $cell[7];
                        $fund = 0;
                    } else {
                        $personal = 0;
                        $fund = 0;
                    }
                    insert(array(
                        "table" => "insure",
                        "field" => array(
                            "id" => suiji(),
                            "stid" => $staff['stid'],//员工ID
                            "subject" => '失业保险',//费款科目
                            "payMoon" => $payMoon,
                            "moon" => $moon,
                            "base" => $cell[6],//缴费基数
                            "personal" => $personal,//个人缴纳
                            "company" => 0,//单位缴帐户
                            "fund" => $fund,//单位缴统筹
                            "type" => $cell[9],//缴费类别
                            "time" => date("Y-m-d H:i:s"),
                        ),
                    ));
                    $x++;
                } else {
                    if ($cell[8] == '单位缴统筹') {
                        $field = array("fund" => $cell[7]);
                    } elseif ($cell[8] == '个人缴纳') {
                        $field = array("personal" => $cell[7]);
                    } else {
                        $field = [];
                    }
                    update(array(
                        "table" => "insure",
                        "field" => $field,
                        "where" => " id = '$insure[id]' ",
                    ));
                    $x++;
                }
            }
            //添加日志
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(array("type" => "insure", "text" => $text));
            //提示
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
        }
        $_SESSION['warn'] = $warn;
        header("location:" . root . "control/adIndex.html?cla=insure&fun=home");
        exit(0);
    }

    /*数据导入分析-导入失业保险-个人补退*/
    public function unemploymentPersonalUpload()
    {
        if (!$this->power(self::page, 'edit')) {
            $warn = L('salary.table.nhmzbjdzx');
        } else {
            $data = $this->importHead(format: [
                3 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $log = "";
            $x = 0;
            foreach ($data as $key => $row) {
                $num = $key + 1;//当前行
                $cell = formSubArray($row);
                $IDCard = $cell[3];//身份证号
                $talent = query('talent_pool', " idCard = '$IDCard'");
                $staff = query("staff", "talentId = '$talent[id]'");
                $payMoon = date("Y-m", strtotime($cell[4] . "01"));//缴款月份
                $moon = date("Y-m", strtotime($cell[5] . "01"));//所属月份
                $insure = query("insure", " stid = '$staff[stid]' and subject = '失业保险个人补退' and payMoon = '$payMoon' and moon = '$moon' ");
                $line = str_replace(['{{i}}'], [$num], L('job.other.line'));
                if (preg_match($this->checkIdCard, $IDCard) == 0) {
                    $log .="\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                } elseif (empty($staff['stid'])) {
                    $log .= "\n" . $line . "：" . L('salary.table.no_staff');
                } elseif (empty($cell[4])) {
                    $log .=  "\n" . $line . "：" . L('salary.table.no_pay_month');
                } elseif (empty($cell[5])) {
                    $log .=  "\n" . $line . "：" . L('salary.table.no_belong_month');
                } elseif (!empty($cell[6]) && preg_match(checkPrice, $cell[6]) == 0) {
                    $log .= "\n" . $line . "：" . L('salary.table.feeBaseError');
                } elseif (empty($insure['id'])) {
                    if ($cell[8] == '单位缴统筹') {
                        $personal = 0;
                        $fund = $cell[7];
                    } elseif ($cell[8] == '个人缴纳') {
                        $personal = $cell[7];
                        $fund = 0;
                    } else {
                        $personal = 0;
                        $fund = 0;
                    }
                    insert(array(
                        "table" => "insure",
                        "field" => array(
                            "id" => suiji(),
                            "stid" => $staff['stid'],//员工ID
                            "subject" => '失业保险个人补退',//费款科目
                            "payMoon" => $payMoon,
                            "moon" => $moon,
                            "base" => $cell[6],//缴费基数
                            "personal" => $personal,//个人缴纳
                            "company" => 0,//单位缴帐户
                            "fund" => $fund,//单位缴统筹
                            "type" => $cell[9],//缴费类别
                            "time" => date("Y-m-d H:i:s"),
                        ),
                    ));
                    $x++;
                } else {
                    if ($cell[8] == '单位缴统筹') {
                        $field = array("fund" => $cell[7]);
                    } elseif ($cell[8] == '个人缴纳') {
                        $field = array("personal" => $cell[7]);
                    } else {
                        $field = [];
                    }
                    update(array(
                        "table" => "insure",
                        "field" => $field,
                        "where" => " id = '$insure[id]' ",
                    ));
                    $x++;
                }
            }
            //添加日志
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(array("type" => "insure", "text" => $text));
            //提示
            $warn = str_replace(['{{$x}}'], [$x], L('job.other.import_warn'));
        }
        $_SESSION['warn'] = $warn;
        header("location:" . root . "control/adIndex.html?cla=insure&fun=home");
        exit(0);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.delInsure');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (static::total(array('table' => 'insure_record', 'where' => " and staffId = '$info[stid]' and month = '$info[payMoon]'"))) {
                    //返回
                    //返回
                    $warn = L('salary.table.scsbykk');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('salary.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{name}}','{{month}}', '{{id}}'], [self::findStaff($info['stid']),$info['moon'], $id], L('salary.table.insure_del_text')) . $warn . "。<br>";

            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.insure_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.insure_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
